package tool

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/golang/protobuf/proto"
	"io/ioutil"
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

func IntInArray(item int, arr []int) (dx int) {
	for idx, v := range arr {
		if v == item {
			dx = idx
			return
		}
	}
	return -1
}

func StringInArray(item string, arr []string) (dx int) {
	for idx, v := range arr {
		if v == item {
			dx = idx
			return
		}
	}
	return -1
}

func RandomStr(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func GetUid(c *gin.Context) int64 {
	uid, ok := c.Get("uid")
	if !ok {
		return 0
	}
	if uidInt64, ok := uid.(int64); ok {
		return uidInt64
	}
	return 0
}

func DataToBytes(d interface{}) (databyte []byte) {
	da, _ := json.Marshal(d)
	databyte = da
	return
}

func DataToString(d interface{}) (datastr string) {
	da, _ := json.Marshal(d)
	datastr = string(da)
	return
}

func BindProto(c *gin.Context, message proto.Message) error {
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		return err
	}
	defer c.Request.Body.Close()
	err = proto.Unmarshal(body, message)
	if err != nil {
		return err
	}
	return nil
}
